import React, { Component } from 'react'
import PropTypes from 'prop-types'
import store from './stateFactory/Store'
import * as Actions from './stateFactory/Actions'
class Counter extends Component {
  // constructor作用：1.初始化state  2.绑定成员函数的this环境
  constructor (props) {
    super(props)
    // 构造函数中通过props获得传入的prop的值
    this.state = this.getOwnState()
    this.onClickIncrementButton = this.onClickIncrementButton.bind(this)
    this.onClickDecrementButton = this.onClickDecrementButton.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  getOwnState () {
    return {
      value: store.getState()[this.props.caption]
    }
  }
  onClickIncrementButton () {
    store.dispatch(Actions.increment(this.props.caption))
  }
  onClickDecrementButton () {
    store.dispatch(Actions.decrement(this.props.caption))
  }
  onChange () {
    this.setState(this.getOwnState())
  }
  // 保持组件内state与store中的一致
  componentDidMount () {
    store.subscribe(this.onChange)
  }
  componentWillUnmount () {
    store.unsubscribe(this.onChange)
  }
  render () {
    // 其他函数中通过this.props访问传入的prop的值
    const {caption} = this.props
    return (
      <div>
        <button onClick={this.onClickIncrementButton}>+</button>
        <button onClick={this.onClickDecrementButton}>-</button>
        <span>{caption} Count: {this.state.value}</span>
      </div>
    )
  }
}
// ES6定义的组件类中，可以通过类的propTypes属性来定义prop规格
Counter.propTypes = {
  caption: PropTypes.string,
  initValue: PropTypes.number.isRequired
}
Counter.defaultProps = {
  caption: 'default'
}
export default Counter
